<template>
  <!-- 菜单搜索 -->
  <van-search v-model="searchValue" shape="round" placeholder="搜索菜谱" input-align="center" @search="search"/>

  <!-- <van-loading v-if="loading"/> -->
   <Loading v-if="loading"/>

  <van-row>
    <!-- 左边菜单 -->
    <van-col span="6" v-if="!loading">
      <van-sidebar v-model="active">
        <van-sidebar-item :title="category" v-for="({ category, cookings }, categoryIdx) in menus"
          @click="changeCategory(categoryIdx)" />
      </van-sidebar>
    </van-col>

    <!-- 右侧 -->
    <van-col span="17" class="menu" v-if="!loading">
      <div v-for="{ name, id } in menus[currentCategory]?.cookings" @click="chooseCook(id)">
        <div class="food-name">
          <span>{{ name }}</span>
          <van-icon name="arrow" />
        </div>
        <van-divider />
      </div>
      <VerticalSpace size="30px"/>
    </van-col>


    <Tab active="home"/>

  </van-row>

</template>

<script setup lang="ts">
import req from '@/utils/requests'
import Tab from '@/components/Tab.vue'
import VerticalSpace from '@/components/VerticalSpace.vue'
import Loading from '@/components/Loading.vue'
import {useSearchStore} from '@/stores/search.ts'

// 路由实例
const router = useRouter()
// 激活状态
const active = ref(0)
// 搜索框的内容
const searchStore = useSearchStore()
const searchValue = computed({
  get: () => searchStore.value,
  set: (val: string) => searchStore.setValue(val)
})
// 菜单列表
const menus = ref()
const currentCategory = ref(0)
// 页面是否在读取菜单列表
const loading = ref(true)

// 首页启动读取菜谱列表
onMounted(async () => {
  try {
    const data = await req.get("/api/menus")
    menus.value = data
    loading.value = false
  } catch (error) {
    console.log('响应异常', error)
  }
})

// 改变选定的品类
const changeCategory = (categoryId: number) => {
  console.log(`当前选中的品类: ${categoryId}`)
  currentCategory.value = categoryId
}

// 选中食谱
const chooseCook = (cookId: number) => {
  console.log(`选中的食谱: ${cookId}`)
  router.push(`/detail/${cookId}`)
}

const search = () => {
  router.push(`/search`)
}

</script>

<style scoped>
.menu::before {
  display: block;
  content: ' ';
  margin-bottom: 16px;
}

.food-name {
  display: flex;
  justify-content: space-between;
  position: relative;
  align-items: center;

  .divider {
    position: absolute;
    height: 1px;
    width: 100%;
    top: 100%;
  }

}
</style>
